<script setup lang="ts">
import { employeeApi } from '@/api/sys/employeeApi'
import { BasicForm, useForm } from '@/components/Form'
import { employeeRoleFormSchema } from '@/views/sys/employee/employee.data'
import { BasicModal, useModalInner } from '@/components/Modal'

defineOptions({ name: 'EmployeeRoleModal' })
const emit = defineEmits(['success', 'register'])
const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: employeeRoleFormSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields()
  setModalProps({ confirmLoading: false })

  const res = await employeeApi.detail(data.record.employeeId)
  setFieldsValue({ ...res })
})

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    await employeeApi.assignRoles({ employeeId: values.employeeId, roleIds: values.roleIds })
    closeModal()
    emit('success')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal v-bind="$attrs" :min-height="100" title="用户角色权限" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
